<?php
namespace app\index\controller;
use app\index\validate\WithdrawValidate;
use app\CommonController;
use app\index\middleware\Auth;
use app\model\FinancialLog;
use app\model\PayCoins;
use app\service\CoinAddressService;
use app\service\FinancialLogService;
use app\service\MemberCoinService;
use app\service\MemberService;
use app\service\PayCoinService;
use app\service\WithdrawService;
use think\exception\ValidateException;

class Withdraw extends CommonController
{
    protected $middleware = [Auth::class];

    public function index()
    {
        $withdrawService = $this->app->make(WithdrawService::class);
        if ($this->request->isPost()) {
            $params = $this->request->post();
            $where = [["member_id", "=", $this->request->uid]];
            if (!empty($params["status"])) {
                $status = $params["status"];
                $where[] = ['status', '=', $status];
            }
            $list = $withdrawService->getListWithOutCount($where, "*", ["coin", "address"]);
            $content = $this->fetch("withdraw-ajax", ["list" => $list]);
            $this->result(["data" => $content, "list" => $list]);
        } else {
            return $this->fetch("index");
        }
    }

    public function apply()
    {

        $payCoinService = $this->app->make(PayCoinService::class);
        $payList = $payCoinService->getAll(
            ["withdraw_status" => 1],
            "id,coin_name,fee,fee_type,withdraw_min_num,withdraw_max_num",
            "sort asc"
        );
        foreach ($payList as $key => $v) {
            $fee = $v["fee"];
            if ($v["fee_type"] == PayCoins::PAY_FEE_NUMBER) {
                $payList[$key]["tip"] = "按数量结算手续费{$fee}个";
            } else {
                $payList[$key]["tip"] = "按百分比结算手续费{$fee}%";
            }
        }
        $this->assign("list", $payList);
        $this->assign("customer_link", h_get_customer_url());
        return $this->fetch("apply");
    }

    public function wallet()
    {
        $params = $this->request->post();
        $payCoinService = $this->app->make(PayCoinService::class);
        $res = $payCoinService->get($params["coin_id"], ["id"]);
        if (!$res) {
            $this->error("不存在的币种");
        }
        $addressId = 0;
        $address = "";
        $amount = 0;
        $memberCoinService = $this->app->make(MemberCoinService::class);
        $res = $memberCoinService->getOne(["member_id" => $this->request->uid, "coin_id" => $params['coin_id']], "account_amount,frozen_amount");
        if ($res) {
            $amount = $res->account_amount;
        }
        $coinAddressService = $this->app->make(CoinAddressService::class);
        $where = [
            "member_id" => $this->request->uid,
            "coin_id" => $params['coin_id'],
            "status" => \app\model\CoinAddress::COIN_ADDRESS_STATUS_APPROVED
        ];
        $addressRes = $coinAddressService->getOne($where, "id,address");
        if ($addressRes) {
            $addressId = $addressRes->id;
            $address = $addressRes->address;
        }
        $data = [
            "coin_id" => $params['coin_id'],
            "account_amount" => $amount,
            "address" => $address,
            "address_id" => $addressId
        ];
        $this->result(['data' => $data]);
    }

    public function doWithdraw()
    {
        $data = $this->request->post();
        $mid = $this->request->uid;
        try {
            validate(WithdrawValidate::class)->scene("withDraw")->check($data);
        } catch (ValidateException $e) {
            throw new ValidateException($e->getError());
        }
        $memberService = $this->app->make(MemberService::class);
        $member = $memberService->get($mid, ["status", "audit_status", "trade_passwd"]);
        if ($member->status == \app\model\Member::MEMBER_STATUS_INACTIVE) {
            $this->error("该账号已经被禁用无法提现");
        }
        if ($member->audit_status != \app\model\Member::MEMBER_AUDIT_STATUS_SUCCESS) {
            $this->error("该账号没有被认证通过");
        }
        $password = $data["password"];
        if (!password_verify($password, $member->trade_passwd)) {
            $this->error("提现密码错误");
        }
        $memberCoinService = $this->app->make(MemberCoinService::class);
        $where = [
            "member_id" => $mid,
            "coin_id" => $data['coin_id']
        ];
        $res = $memberCoinService->getOne($where, "account_amount,frozen_amount");
        if (!$res) {
            $this->error("钱包不存在对应的币种");
        }
        $coinAddressService = $this->app->make(CoinAddressService::class);
        $where = [
            "member_id" => $mid,
            "coin_id" => $data['coin_id'],
            "status" => \app\model\CoinAddress::COIN_ADDRESS_STATUS_APPROVED
        ];
        $addressRes = $coinAddressService->getOne($where, "id,address");
        if (!$addressRes) {
            $this->error("当前币种对应的提现地址不存在");
        }
        $payCoinService = $this->app->make(PayCoinService::class);
        $res = $payCoinService->get($data["coin_id"], ["id", "withdraw_min_num", "withdraw_max_num", "fee", "fee_type"]);
        if (!$res) {
            $this->error("提现币种不存在");
        }
        if ($data["num"] < $res->withdraw_min_num) {
            $this->error("提现金额不能小于{$res->withdraw_min_num}");
        }
        if ($data["num"] > $res->withdraw_max_num) {
            $this->error("提现金额不能大于{$res->withdraw_max_num}");
        }
        $fee = $res->fee;
        $feeType = $res->fee_type;
        if ($feeType == PayCoins::PAY_FEE_PERCENT) {
            $fee = $data["num"] * $res->fee / 100;
        }
        $financialLogService = $this->app->make(FinancialLogService::class);
        $withdrawService = $this->app->make(WithdrawService::class);
        $withdrawService->transaction(function () use ($data, $financialLogService, $mid, $withdrawService, $fee) {
            $num = floatval($data["num"]);
            $financialLogService->flowLog($mid, -$num, $data["coin_id"], $num, FinancialLog::WITHDRAW_FROZE, '申请提币冻结金额');
            $params["member_id"] = $mid;
            $params["num"] = $data['num'];
            $params["receive_num"] = $data["num"] - $fee;
            $params["coin_id"] = $data['coin_id'];
            $params["fee"] = $fee;
            $params["address_id"] = $data['address_id'];
            $params["status"] = \app\model\Withdraw::WITHDRAW_STATUS_APPENDING;
            $params["order_sn"] = h_create_order_no('T');
            $withdrawService->save($params);
        });
        $this->success("申请成功");

    }
}